package com.wondream.myframework.juc;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wondream
 * @version 1.0
 * @create 2022/5/22 4:35 PM
 */
public class JUC04AtomicIntegerWithLock {

    private int value;
    private Lock lock = new ReentrantLock();
    public JUC04AtomicIntegerWithLock(int value) {
        this.value = value;
    }

    public final int get(){
        lock.lock();
        try {
            return value;
        } finally {
            lock.unlock();
        }
    }

    public final void set(int newValue){
        lock.lock();
        try {
            value = newValue;
        } finally {
            lock.unlock();
        }
    }

    public final int getAndSet(int newValue){
        lock.lock();
        try {
            int ret = value;
            value = newValue;
            return ret;
        } finally {
            lock.unlock();
        }
    }

    public final boolean compareAndSet(int expect, int newValue){
        lock.lock();
        try {
            if (value==expect) {
                value = newValue;
                return true;
            } else {
                return false;
            }
        } finally {
            lock.unlock();
        }
    }

    public final int getAndIncrement(){
        lock.lock();
        try {
            return value++;
        } finally {
            lock.unlock();
        }
    }

    public final int getAndDecrement(){
        lock.lock();
        try {
            return value--;
        } finally {
            lock.unlock();
        }
    }

    public final int incrementAndGet(){
        lock.lock();
        try {
            return ++value;
        } finally {
            lock.unlock();
        }
    }

    public final int decrementAndGet(){
        lock.lock();
        try {
            return --value;
        } finally {
            lock.unlock();
        }
    }

    public String toString(){
        return Integer.toString(get());
    }
}
